
# expects the provider to be answer the following messages
# rows() - the number of rows of data
# cols() - the number of columns
# headings() - name of each column
# place_content(html, row, colname)

class TableBrowser < Pan::Component
  attr_accessor :visible_rows, :element_id
  def initialize(provider)
    @provider = provider
    @current_row = 0
    @visible_rows = 10
  end
  
  def get_meta_data
    @rows = @provider.rows()
    @cols = @provider.cols()
    @col_headings = @provider.headings()
  end

  def rows_in_view
    max = [@current_row+@visible_rows,@rows].min
    (@current_row..max-1).to_a
  end

  def render_on(html)
    get_meta_data()
    # html.heading("#{@provider.class}",3)
    html.div("class"=>"table-nav-button") {
      if @current_row == 0
        html.span("class"=>"disabled") { html.text("prev") }
      else
        html.link("prev") {
          @current_row = [@current_row - @visible_rows,0].max
        }
      end
    }
    html.div("class"=>"table-nav-button clear") {
      if @current_row + @visible_rows < @rows
        html.link("next") {
          @current_row += @visible_rows 
        }
      else
        html.span("class"=>"disabled") { html.text("next") }
      end
    }
    html.lit(sprintf("Progress: %2.0f",(@current_row.to_f/@rows)*100))
    html.table("border"=>"0","cellspacing"=>"0","class"=>"clear-both") {
      html.thead {
        html.tr('class'=>"header") {
          @provider.headings.each { |heading|
            html.th { 
              html.link(heading) { @provider.sort_by(heading) }
            }
        }
        }
      }
      html.tbody {
        render_rows_on(html)
      }
    }
  end

  def render_rows_on(html)
    rows_in_view().each_with_index do |row, row_number|
      html.tr {
        @provider.headings.each do |colname|
          html.td("class"=>row%2==0?"":"alt") {
            @provider.place_content(html,row,colname)
          }
        end
      }
    end
  end


end
